// http 模块  实现web服务
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const { log } = require('console');
// 创建服务 
 // 全部以/static 开头      
    // html   /static/views/home.html
    // css   /static/style/home.css
    // js    /static/js/detail.js
const server = http.createServer((req,res)=>{
    // console.log(url.parse(req.url));
    const {pathname} = url.parse(req.url);
    const {method} = req;  
    // console.log(pathname);///static/views/home.html
    if(/^\/static/.test(pathname)){
        const {ext,base} = path.parse(pathname); //
        // base  home.html  home.css   
        // ext    .html .css .js
        // console.log(path.parse(pathname));
        // html  css  js 都属于静态资源 

        
        console.log(ext);// .html
        console.log(base);// home.html
        let filepath = 'C:/www/2303/day39/client/'
        switch(ext){
            case '.html':  // 如果是.html 就到 /client/views下面去找 
                filepath += 'views/';
                break
            case '.css':// 如果是.css 就到 /client/css下面去找 
                filepath += 'css/';
                break
            case '.js': // 如果是.js 就到 /client/js下面去找
                filepath += 'js/';
                break 
        }
        // filepath   C:/www/2303/day39/client/views
        // console.log(filepath+base);
        // C:/www/2303/day39/client/views/home.html 
        filepath+=base;
        fs.readFile(filepath,'utf-8',(err,data)=>{
            if(err){
                fs.readFile('C:\\www\\2303\\day39\\client\\views\\404.html','utf-8',(e,d)=>{res.end(d)})
                return
            }

            res.end(data)
        })
        
    }
    
    if(/^\/api/.test(pathname)){
        if(pathname === '/api/goods/list' && method === 'GET'){
            const info = {
                code:1,
                message:'请求商品列表成功',
                list:[{id:1},{id:2},{id:3}]
            }

            res.end(JSON.stringify(info))
        }
    }
    

})



//启动服务 监听用户访问

server.listen(8081,()=>{
    console.log('组合服务启动成功,正在监听8081端口');
})


// express 
// koa 